// pages/addAddress/addAddress.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  regions: {},
  data: {
    region: ['', '请选择所在地区', ''],
    customItem: '全部',
    name: '',
    tel: '',
    place: '', // 详细地址
    houseNumber: '',
    setDefault: false,
    defaultHide: true,
    regionId: [],
    address_id: null,
    is_default: null,
    lat: '',
    lng: '',
    multiArray: [],
    multiIndex: [0, 0, 0],
    multiArrId: []
  },

  // 选择定位（已授权用户定位情况下调用）
  chooseLocation(lat, lng) {
    const that = this;
    wx.chooseLocation({
      latitude: lat,
      longitude: lng,
      success(res) {
        that.setData({
          place: res.name,
          lat: res.latitude,
          lng: res.longitude
        })
      }
    })
  },

  // 打开定位获取详细地址
  place() {
    const that = this;
    that.chooseLocation()
    // wx.getLocation({
    //   type:'gcj02',
    //   success(locationRes){
    //     console.log(locationRes,55555)
    //     that.chooseLocation(locationRes.latitude,locationRes.longitude)
    //   },
    //   fail(err){
    //     if (err.errMsg.includes('getLocation:fail auth deny')) {
    //       wx.showModal({
    //         title: '授权提示',
    //         content: '需要获取您的位置信息，请在设置中开启位置权限',
    //         showCancel: false,
    //         success: (modalRes) => {
    //           if (modalRes.confirm) {
    //             wx.openSetting({
    //               success(settingRes) {
    //                   if (settingRes.authSetting['scope.userLocation']) {
    //                     wx.getLocation({
    //                       // type:'gcj02',
    //                       success(locationRes){
    //                         that.chooseLocation(locationRes.latitude,locationRes.longitude)
    //                       },
    //                     });
    //                   } else {
    //                     wx.showToast({ title: '未授权位置信息', icon: 'none' })
    //                   }
    //               }
    //             })
    //           }
    //         }
    //       })
    //     } else {
    //       console.log('获取位置失败', err)
    //     }
    //   }
    // })


    // if (that.data.locationAuthorization) {
    //   that.chooseLocation()
    // } else {
    //   wx.openSetting({
    //     success(res) {
    //       app.globalData.locationAuthorization = res.authSetting['scope.userLocation'];
    //       that.setData({
    //         locationAuthorization: res.authSetting['scope.userLocation']
    //       })
    //       if (res.authSetting['scope.userLocation']) {
    //         that.chooseLocation()
    //       }
    //     }
    //   })
    // }
  },
  // 获取姓名输入内容
  changeName(e) {
    const that = this;
    that.setData({
      name: e.detail.value
    })
  },
  // 获取电话输入内容
  changeTel(e) {
    const that = this;
    that.setData({
      tel: e.detail.value
    })
  },

  // 获取门牌号输入内容
  changeHouseNumber(e) {
    const that = this;
    that.setData({
      houseNumber: e.detail.value
    })
  },
  // 默认地址
  switch1Change(e) {
    const that = this;
    that.setData({
      setDefault: e.detail.value
    })
  },

  // 提交表单
  saveAddress() {

    const that = this;
    const token = app.globalData.token;
    let data = {
      name: that.data.name,
      province: that.data.regionId[0],
      city: that.data.regionId[1],
      district: that.data.regionId[2],
      address: that.data.place,
      mobile: that.data.tel,
      houseNumber: that.data.houseNumber,
      address_id: that.data.address_id
    }
    if (data.name == '') {
      app.showInfo('请输入收货人');
      return false;
    } else if (data.mobile == '') {
      app.showInfo('请输入手机号码');
      return false;
    } else if (data.address == '') {
      app.showInfo('请输入详细地址');
      return false;
    } else if (data.houseNumber == '') {
      app.showInfo('请输入门牌号');
      return false;
    }
    // 🌈立志做个万元户
    let specialName = that.hasSpecial(that.data.name);
    // 判断备注是否包含特殊字符
    if (specialName) {
      wx.showModal({
        showCancel: false,
        content: '您的名字中包含特殊字符，请正确输入',
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定');
          }
        }
      })
      return false
    }
    let json = {
      address_id: data.address_id ? data.address_id : 0,
      token: token,
      consignee: data.name,
      address: data.address + "|" + data.houseNumber,
      mobile: data.mobile,
      latitude: that.data.lat,
      longitude: that.data.lng,
      is_default: that.data.setDefault == true ? 1 : 0,
      coordinate: 'GCJ02',
      province: that.data.multiArrId[0],
      city: that.data.multiArrId[1],
      district: that.data.multiArrId[2],
    };
    let jsonData = app.utils.getSignData(json); // 添加签名
    that.setData({
      hiddenLoading: false
    })
    app.utils.post(app.api.reqUrls.addAddress, jsonData).then(res => { //将数据post到服务端进行处理
      that.setData({
        hiddenLoading: true
      })
      if (res.status == 1) {
        if (json.address_id===0 && that.data.where == "fillOrder") {
          let json = {
            address_id:res.result,
            token: app.globalData.token,
            coordinate: 'GCJ02'
          }
          let jsonData = app.utils.getSignData(json); // 添加签名
          app.utils.post(app.api.reqUrls.addresslist, jsonData).then((resList) => {
            if (res.status == 1) {
              let address = resList.result[0];
              let id = address.address_id;
              let pages = getCurrentPages();
              let currPage = null; //当前页面
              let prevPage = null; //上二个页面
              if (pages.length >= 3) {
                currPage = pages[pages.length - 1]; //当前页面
                prevPage = pages[pages.length - 3]; //上二个页面
              }
              if (prevPage) {
                address.total_address = address.province_name + address.city_name + address.district_name + address.address
                prevPage.setData({
                  [`orderData.addressList`]: address,
                  [`orderData.addressList.address_id`]: id,
                  isDefault: false,
                  iseduitadd: false
                });
                wx.navigateBack({
                  delta: 2
                })
              }
            }
          }).catch(err => {
            app.showInfo(err.toString());
            that.setData({
              hiddenLoading: true
            })
          })
        } else {
          wx.navigateBack({ // 返回上一页面
            delta: 1
          })
        }
      } else {
        throw res.msg
      }

    }).catch(err => {
      app.showInfo(err.toString())
      that.setData({
        hiddenLoading: true
      })
    })
  },
  // 判断姓名中是否有表情
  hasSpecial(substring) {
    if (substring) {
      // 判断是否有表情
      var reg = /[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/ig
      if (reg.test(substring)) {
        return true;
      }
      // 判断是否有特殊字符
      var regs = /^[\u4e00-\u9fa5_a-zA-Z0-9]+$/;
      if (!regs.test(substring)) {
        return true;
      }
    }
  },
  // 加载地址数据
  newData() {
    const that = this;
    const token = app.globalData.token;
    let json = {
      token: token,
    }
    let jsonData = app.utils.getSignData(json); // 添加签名
    app.utils.post(app.api.reqUrls.getParentRegion, jsonData).then((data) => {
      that.setData({
        hiddenLoading: true
      })
      if (data.status == 1) {
        that.init(data.result.retions)
      } else {
        throw res.msg
      }
    }).catch(err => {
      app.showInfo(err.toString())
      that.setData({
        hiddenLoading: true
      })
    })
  },
  init(regions) {
    if (Object.keys(regions).length > 0) {
      const _this = this
      _this.regions = regions
      let multiIndex = [0, 0, 0];
      let multiArrId = _this.data.multiArrId;
      let pid = 0;
      for (let i = 0; i < multiArrId.length; i++) {
        if (i > 0 && pid != multiArrId[i - 1]) {
          break;
        }
        _this.regions[pid].forEach((value, index) => {
          if (value.id == multiArrId[i]) {
            multiIndex[i] = index;
          }
        })
        pid = multiArrId[i]
      }
      _this.setData({
        multiIndex: multiIndex,
        multiArrId: multiArrId
      })
      _this.setChoose()
    }
  },
  setChoose() {
    const _this = this
    let multiArray = [];
    let multiArrId = [];
    let pid = 0;
    for (let i = 0; i < _this.data.multiIndex.length; i++) {
      _this.regions[pid].forEach((value, index) => {
        if (_this.data.multiIndex[i] == index) {
          multiArray[i] = _this.regions[pid];
          multiArrId.push(value.id);
          pid = value.id
        }
      })

    }
    _this.setData({
      multiArray: multiArray,
      multiArrId: multiArrId
    })
  },
  bindMultiPickerChange: function (e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value, this.data.multiArrId, 999999)
  },
  bindMultiPickerColumnChange: function (e) {
    // console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
    let multiIndex = this.data.multiIndex

    for (let i = 0; i < multiIndex.length; i++) {
      if (i == e.detail.column) {
        multiIndex[e.detail.column] = e.detail.value
      }
      if (i > e.detail.column) {
        multiIndex[i] = 0
      }
    }
    this.setData({
      multiIndex: multiIndex
    })
    this.setChoose()
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this;
    // 加载省市区
    that.newData()
    let newId = options.id;
    // 新建收货地址
    if (!newId || newId == 'news') {
      that.setData({
        defaultHide: false,
        hiddenLoading: true,
        name: '',
        tel: app.globalData.userInfo.mobile,
        where: options.where || ''
      })
      // 更改收货地址
    } else {
      that.setData({
        defaultHide: false,
        address_id: newId
      })
      const token = app.globalData.token;
      let json = {
        address_id: newId,
        token: token,
      }
      let jsonData = app.utils.getSignData(json);
      app.utils.post(app.api.reqUrls.addresslist, jsonData).then((data) => {
        that.setData({
          hiddenLoading: true
        })
        let res = data.result && data.result.length > 0 ? data.result[0] : undefined
        // let res = data.result.filter((data) => {
        //   return data.address_id == newId
        // })
        // 判断是否为默认地址
        if (res) {
          let setDefault = res.is_default == 1
          // 把详细地址和门牌号拆分
          let arr = res.address.split('|')
          let multiArrId = []
          multiArrId.push(res.province)
          multiArrId.push(res.city)
          multiArrId.push(res.district)
          that.setData({
            setDefault: setDefault,
            multiArrId,
            name: res.consignee,
            tel: res.mobile,
            place: arr && arr[0] ? arr[0] : '',
            houseNumber: arr && arr[1] ? arr[1] : '',
            is_default: res.is_default,
            'region[0]': res.province_name,
            'region[1]': res.city_name,
            'region[2]': res.district_name,
            'regionId[0]': res.province,
            'regionId[1]': res.city,
            'regionId[2]': res.district,
            lat: res.latitude,
            lng: res.longitude
          })
        }
      })
    }
  },
})